<template>
  <div>
    <div class="cards">
      <el-button type="warning" style="margin-right: 20px" @click="delBatch">批量删除</el-button>
    </div>
    <div class="card" style="margin-top: 10px">
      <el-table
          :data="data.tableData"
          @selection-change="handleSelectionChange"
          stripe
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="Id" align="center"></el-table-column>
        <el-table-column prop="userId" label="用户Id" align="center"></el-table-column>
        <el-table-column prop="oldRole" label="用户" align="center"></el-table-column>
        <el-table-column prop="newRole" label="申请角色" align="center"></el-table-column>
        <el-table-column prop="applyDate" label="时间" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" align="center"></el-table-column>
        <el-table-column prop="reason" label="原由" align="center"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
                @click="handleUpdate(scope.row)"
                type="primary"
                circle
            >
              √
            </el-button>
            <el-button
                @click="handleDelete(scope.row.id)"
                type="danger"
                :icon="Delete"
                circle
            />
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 10px">
        <el-pagination
            @current-change="load"
            @size-change="load"
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
        ></el-pagination>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="data.formVisible"
        :title="data.form.id ? '编辑用户信息' : '新增用户信息'"
        width="500"
        style="margin-top: 2%"
    >
      <el-form
          :model="data.form"
          style="width: 400px; margin: 0 auto; display: flex; flex-direction: column; align-items: flex-start;"
      >
        <el-form-item label="用户" prop="oldRole"    >
          <el-input v-model="data.form.oldRole" placeholder="用户" disabled></el-input>
        </el-form-item>
        <el-form-item label="申请角色" prop="newRole">
          <el-input v-model="data.form.newRole" placeholder="申请角色" disabled></el-input>
        </el-form-item>
        <el-form-item label="时间" prop="applyDate">
          <el-date-picker v-model="data.form.applyDate" type="datetime" placeholder="选择时间" disabled></el-date-picker>
        </el-form-item>
        <el-form-item label="原由" prop="reason">
          <el-input type="textarea" v-model="data.form.reason" placeholder="原由" disabled></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="data.form.status">
            <el-radio  label="通过">通过</el-radio>
            <el-radio  label="不通过">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { reactive, onMounted } from "vue";
import { Search, Delete, Edit } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  ids: []
});

// 加载数据
const load = () => {
  request.get("/apply/selectByPage", {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize
    }
  }).then((res) => {
    console.log(res);
    if (res.code === 200) {
      data.tableData = res.data.list || [];
      data.total = res.data.total || 0;
    } else {
      ElMessage.error(res.msg || "加载失败");
      data.tableData = [];
      data.total = 0;
    }
  }).catch((error) => {
    ElMessage.error("加载失败，请稍后再试");
    console.error("加载失败", error);
    data.tableData = [];
    data.total = 0;
  });
};

onMounted(() => {
  load();
});

// 新增
const handleAdd = () => {
  data.formVisible = true;
  data.form = {};
};

// 编辑
const handleUpdate = (row) => {
  data.form = JSON.parse(JSON.stringify(row)); // 深拷贝
  data.formVisible = true;
};

// 保存（新增或编辑）
const save = () => {
  if (data.form.id) {
    update();
  } else {
    add();
  }
};

const add = () => {
  request.post("apply/add", data.form).then((res) => {
    if (res.code === 200) {
      data.formVisible = false;
      ElMessage.success("添加成功");
      load();
    } else {
      ElMessage.error(res.message);
    }
  });
};

const update = () => {
  request.put("apply/update", data.form).then((res) => {
    if (res.code === 200) {
      data.formVisible = false;
      ElMessage.success("修改成功");
      load();
    } else {
      ElMessage.error(res.message);
    }
  });
};

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm("删除数据后无法恢复，您确认删除吗？", "温馨提示", {
    type: "warning"
  }).then(() => {
    request.delete(`apply/delete/${id}`).then((res) => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.message);
      }
    });
  }).catch(() => {
    // 用户取消删除
  });
};

// 批量删除
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm("删除数据后无法恢复，您确认删除吗？", "温馨提示", {
    type: "warning"
  }).then(() => {
    request.delete("apply/delete/batch", { data: data.ids }).then((res) => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.message);
      }
    });
  }).catch(() => {
    // 用户取消删除
  });
};

// 多选
const handleSelectionChange = (rows) => {
  data.ids = rows.map((row) => row.id);
};
</script>

<style scoped>
.cards {
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.12);
}

/* 调整表单元素的间距 */
.el-form-item {
  margin-bottom: 15px;
}

/* 可以对dialog的底部操作按钮部分进行样式微调 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>
